// 订货单

<template>
  <view class="page">
    <dht-empty type="no_goods" class="nodata-box" v-if="noData"></dht-empty>
    <template v-else>
      <!-- 管理 -->
      <view class="manager-box">
        <view @tap="isManage = !isManage">{{ isManage ? '完成' : '管理' }}</view>
      </view>
      <!-- 商品 -->
      <view class="goods-box">
        <view
          class="goods-item"
          v-for="(item, index) in cartList"
          :key="item.id"
          @tap="goDetail(item.goods_id)"
        >
          <view class="item-left">
            <view class="item-check" @tap.stop>
              <u-checkbox
                active-color="#fe492f"
                size="40"
                shape="circle"
                v-model="item.checked"
                @change="goodsCheckedChange"
              ></u-checkbox>
            </view>
            <view class="item-img">
              <image
                :class="item.goods.goods_image ? '' : 'no-image'"
                :src="item.goods.goods_image"
              />
            </view>
          </view>
          <view class="item-right">
            <view class="item-top">
              <view class="item-title">{{ item.goods.goods_name }}</view>
              <view class="item-spec">
                {{ item.goods.unit_name + (item.goods.attr_name ? '; ' : '') }}
                {{ item.goods.attr_name }}
              </view>
            </view>
            <view class="item-bottom">
              <view class="item-money">
                <template v-if="priceStatus">
                  {{
                    item.goods.price !== '' && bind
                      ? '￥' + item.goods.price + '.' + item.goods.decimal
                      : ''
                  }}
                </template>
              </view>

              <view class="item-btn" @tap.stop>
                <text class="iconfont icon-a--" @tap="subNumber(item.id, item.number)"></text>
                <view class="item-number">
                  <input
                    type="text"
                    v-model.number="item.number"
                    @focus="numberInputFocus(item.number)"
                    @change="numberInputChange(index, item.id, item.number, $event)"
                  />
                </view>
                <text class="iconfont icon-a-1" @tap="addNumber(item.id, item.number)"></text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 提交 -->
      <view class="submit-box">
        <view class="submit-left">
          <u-checkbox
            active-color="#fe492f"
            size="40"
            shape="circle"
            @change="allCheckedChange"
            v-model="allChecked"
          >
            全选
          </u-checkbox>
        </view>
        <view class="submit-right">
          <view class="submit-count" v-if="!isManage">
            <text class="text1" v-if="bind && priceStatus">
              合计：<text style="font-weight: 700; color: #fe492f">{{ totalPrice }}</text> 元
            </text>
            <text class="text2">一共{{ totalNumber }}件</text>
          </view>
          <view class="submit-btn" :class="hasChecked ? 'select' : 'unselect'" @tap="submit">
            {{ isManage ? '删除' : '提交' }}
          </view>
        </view>
      </view>
    </template>
    <!-- 地址弹窗 -->
    <view class="popup-box" v-show="chooseAddressDialog">
      <view class="popup-mask" @tap="chooseAddressDialog = false" @touchmove.stop></view>
      <view class="popup-address">
        <view class="address-title">请选择收货地址</view>
        <view class="address-text">
          <view class="address-text-no" v-if="!defaultAddress">无默认收货地址</view>
          <view class="address-text-yes" v-else @tap="toAddressPage">
            <text>
              {{
                defaultAddress.province_name +
                defaultAddress.city_name +
                defaultAddress.area_name +
                defaultAddress.detail_address
              }}
            </text>
            <text class="iconfont icon-jiantou"></text>
          </view>
        </view>
        <view class="address-btn">
          <view class="btn btn1" @tap="chooseAddressDialog = false">取消</view>
          <view class="btn btn2" v-if="!defaultAddress" @tap="toAddressPage">去添加</view>
          <view class="btn btn2" v-else @tap="confirm">确定</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data() {
    return {
      noData: false,
      noDataImg: require('@/static/image/购物车.png'),
      allChecked: false,
      hasChecked: false,
      isManage: false,
      bind: false,
      totalPrice: 0,
      totalNumber: 0,
      cartList: [],
      oldNumber: '',
      defaultAddress: null,
      chooseAddressDialog: false,
      addressId: ''
    }
  },
  onLoad() {
    uni.$on('chooseAddress', ({ item }) => {
      this.defaultAddress = item
      this.addressId = item.id
    })
    this.getAddress()
  },
  async onShow() {
    this.allChecked = false
    const userInfo = uni.getStorageSync('userInfo')
    this.bind = userInfo.binding == 1
    this.getCartList()
  },
  methods: {
    // 获取收货地址
    async getAddress() {
      const res = await this.$http.post('/api/kuerp/order/address/getlist', {
        page: 1
      })
      if (res.code == 200) {
        let addressList = res.data.list
        const filterRes = addressList.filter((item) => item.is_default == '1')
        if (filterRes.length) {
          this.defaultAddress = filterRes[0]
          this.addressId = filterRes[0].id
        } else {
          this.defaultAddress = null
        }
      }
    },
    // 获取购物车列表
    async getCartList() {
      const res = await this.$http.post('/api/kuerp/order/index/getCart')
      if (res.code == 200) {
        res.data.forEach((item) => {
          this.cartList.forEach((item1) => {
            if (item.id === item1.id) {
              item.checked = item1.checked
            }
          })
          if (item.goods.goods_image) {
            item.goods.goods_image = item.goods.goods_image.startsWith('http')
              ? item.goods.goods_image
              : this.$baseURL + item.goods.goods_image
          }
        })

        this.cartList = res.data
        this.allChecked = this.cartList.every((item) => item.checked)
        this.getTotal()
      } else {
        this.cartList = []
      }
      this.hasChecked = this.cartList.some((item) => item.checked)
      this.noData = this.cartList.length === 0 ? true : false
      this.getCartNumber()
    },
    // 获取购物车数量
    async getCartNumber() {
      const res = await this.$http.post('/api/kuerp/order/index/getCartNumber')
      if (res.code == 200) {
        if (res.data === 0) {
          uni.removeTabBarBadge({ index: 2 })
        } else {
          uni.setTabBarBadge({
            index: 2,
            text: res.data + ''
          })
        }
      }
    },
    // 计算价格 & 数量
    getTotal() {
      this.totalPrice = 0
      this.totalNumber = 0
      const filterRes = this.cartList.filter((item) => item.checked)
      if (filterRes.length) {
        filterRes.forEach((item) => {
          this.totalNumber += item.number
          this.totalPrice += +item.number * (item.goods.price + '.' + item.goods.decimal)
        })
        this.totalPrice = this.totalPrice.toFixed(filterRes[0].goods.decimal.length)
      }
    },
    // 监听输入框获取焦点
    numberInputFocus(number) {
      this.oldNumber = number
    },
    // 监听输入框改变
    async numberInputChange(index, id, number, e) {
      if (this.oldNumber === number) return

      if (!e.detail.value || e.detail.value === '0') {
        this.cartList[index].number = this.oldNumber
        return
      }

      const res = await this.$http.post('/api/kuerp/order/index/editCart', {
        cart_id: id,
        number
      })
      if (res.code == 200) {
        this.getCartList()
        uni.$emit('refreshCategoryPage')
      }
    },
    // 加
    async addNumber(id, number) {
      const res = await this.$http.post('/api/kuerp/order/index/editCart', {
        cart_id: id,
        number: ++number
      })
      if (res.code == 200) {
        this.getCartList()
        uni.$emit('refreshCategoryPage')
      }
    },
    // 减
    async subNumber(id, number) {
      if (number === 1) {
        return uni.showModal({
          title: '提示',
          content: '是否确认删除？',
          success: async ({ confirm }) => {
            if (confirm) {
              const res = await this.$http.post('/api/kuerp/order/index/delCart', {
                cart_id: id
              })
              if (res.code == 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.getCartList()
                uni.$emit('refreshCategoryPage')
              }
            }
          }
        })
      } else {
        const res = await this.$http.post('/api/kuerp/order/index/editCart', {
          cart_id: id,
          number: --number
        })
        if (res.code == 200) {
          this.getCartList()
          uni.$emit('refreshCategoryPage')
        }
      }
    },
    // 全选
    allCheckedChange(e) {
      this.hasChecked = e.value
      this.cartList.forEach((item) => {
        item.checked = e.value
      })
      this.getTotal()
    },
    // 单选
    goodsCheckedChange() {
      setTimeout(() => {
        this.allChecked = this.cartList.every((item) => item.checked)
        this.hasChecked = this.cartList.some((item) => item.checked)
        this.getTotal()
      }, 10)
    },
    // 前往商品详情
    goDetail(id) {
      uni.navigateTo({ url: `/pages/home/homeGoods/goodsDetail?id=${id}` })
    },
    // 提交 OR 删除
    async submit() {
      if (!this.hasChecked) return
      if (this.isManage) {
        uni.showModal({
          title: '提示',
          content: '是否确认删除？',
          success: async ({ confirm }) => {
            if (confirm) {
              let select = []
              this.cartList.forEach((item) => {
                if (item.checked) {
                  select.push(item.id)
                }
              })
              select = select.join(',')
              const res = await this.$http.post('/api/kuerp/order/index/delCart', {
                cart_id: select
              })
              if (res.code == 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.getCartList()
                uni.$emit('refreshCategoryPage')
              }
            }
          }
        })
      } else {
        if (!this.bind) {
          return uni.showModal({
            title: '提示',
            content: '提交订货单需绑定手机',
            confirmText: '去绑定',
            success: ({ confirm }) => {
              if (confirm) {
                uni.navigateTo({
                  url: '/pages/my/commonFunction/accountManagement/bindPhone'
                })
              }
            }
          })
        }

        // 开启订阅
        const res1 = await this.$http.post('/api/kuerp/order/config/getConfig', {
          name: 'template_xd'
        })
        const res2 = await this.$http.post('/api/kuerp/order/config/getConfig', {
          name: 'template_sh'
        })
        const res3 = await this.$http.post('/api/kuerp/order/config/getConfig', {
          name: 'template_fh'
        })

        uni.requestSubscribeMessage({
          tmplIds: [res1.data.template_xd, res2.data.template_sh, res3.data.template_fh],
          success(res) {},
          fail(err) {},
          complete: () => {
            const ids = []
            this.cartList.forEach((item) => {
              if (item.checked) ids.push(item.id)
            })
            uni.navigateTo({
              url: `/pages/shopping/submit?ids=${JSON.stringify(ids)}`
            })
          }
        })
      }
    },
    // 确认提交
    async confirm() {
      this.chooseAddressDialog = false
      let postForm = []
      this.cartList.forEach((item) => {
        if (item.checked) {
          postForm.push(item.id)
        }
      })
      postForm = postForm.join(',')
      const res = await this.$http.post('/api/kuerp/order/index/createOrder', {
        cart_id: postForm,
        address_id: this.addressId
      })
      if (res.code == 200) {
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })
        uni.$emit('refreshCategoryPage')
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/shopping/result' })
        }, 600)
      }
    },
    toAddressPage() {
      uni.navigateTo({
        url: '/pages/my/commonFunction/address/index?type=choose'
      })
    }
  },
  computed: {
    ...mapState(['priceStatus'])
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  padding-bottom: 140rpx;
  padding-top: 88rpx;
  background-color: #f7f7f7;
}

// 无数据
.nodata-box {
  margin-top: 342rpx;
  text-align: center;
}

// 管理
.manager-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 88rpx;
  padding-right: 24rpx;
  background-color: #f7f7f7;
  z-index: 9999;
  view {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 120rpx;
    height: 48rpx;
    background: #ffffff;
    border-radius: 24rpx;
    color: #888888;
  }
}

// 商品
.goods-box {
  .goods-item {
    display: flex;
    margin: 20rpx auto 0;
    width: 702rpx;
    height: 248rpx;
    background: #ffffff;
    border-radius: 12rpx;
    &:first-child {
      margin-top: 0;
    }
    .item-left {
      display: flex;
      align-items: center;
      .item-check {
        margin-left: 14rpx;
      }
      .item-img {
        display: flex;
        align-items: center;
        image {
          width: 200rpx;
          height: 200rpx;

          border-radius: 12rpx;
        }
        .no-image {
          background: #d8d8d8;
        }
      }
    }
    .item-right {
      flex: 1;
      display: flex;
      justify-content: space-between;
      // align-items: center;
      flex-direction: column;
      padding: 44rpx 24rpx 22rpx 20rpx;
      .item-top {
        .item-title {
          color: #333333;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        .item-spec {
          color: #999999;
          margin-top: 10rpx;
        }
      }
      .item-bottom {
        display: flex;
        justify-content: space-between;
        // align-items: center;
        .item-money {
          font-weight: 500;
          color: #ff1100;
        }

        .item-btn {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          .iconfont {
            color: #ccc;
            font-size: 48rpx;
          }
          .item-number {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 16rpx;
            width: 100rpx;
            height: 48rpx;
            background: #f4f4f4;
            border-radius: 12rpx;
            font-weight: 500;
            color: #111111;
            input {
              text-align: center;
            }
          }
        }
      }
    }
  }
}

// 提交
.submit-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  left: 0;
  bottom: 0;
  padding-left: 38rpx;
  width: 100%;
  height: 120rpx;
  background: #ffffff;
  z-index: 99999;
  .submit-left {
  }
  .submit-right {
    display: flex;
    .submit-count {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-end;
      margin-right: 20rpx;
      .text1 {
        color: #333333;
      }
      .text2 {
        font-size: 24rpx;
        color: #888888;
      }
    }
    .submit-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 200rpx;
      height: 120rpx;
      font-size: 32rpx;
      color: #fff;
      &.select {
        background-color: #fe492f;
      }
      &.unselect {
        background-color: #ddd;
      }
    }
  }
}

// 地址弹窗
.popup-box {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 99999;
}
.popup-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
}
.popup-address {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 76rpx 0 32rpx;
  width: 570rpx;
  height: 378rpx;
  background: #ffffff;
  border-radius: 20rpx;
  .address-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
  }
  .address-text {
    font-size: 32rpx;
    .address-text-no {
      color: #666666;
    }
    .address-text-yes {
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      color: #fe3d23;
      text {
        &:first-child {
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
      }
      .iconfont {
        font-size: 26rpx;
        margin-left: 8rpx;
      }
    }
  }
  .address-btn {
    display: flex;
    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 9rpx;
      width: 244rpx;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 32rpx;
      font-weight: 600;
    }
    .btn1 {
      color: #333333;
      border: 1px solid #cccccc;
    }
    .btn2 {
      color: #ffffff;
      background: #f74444;
    }
  }
}
</style>
